import sys
import uvicorn
import socket
from app.core.config import settings

def check_port(host: str, port: int) -> bool:
    """
    Check if a port is available.
    :param host: Host address
    :param port: Port number
    :return: True if port is available, False if occupied
    """
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
            sock.settimeout(1)
            # connect_ex returns 0 if successful (port is open/occupied)
            result = sock.connect_ex((host, port))
            return result != 0 
    except Exception:
        return False

def find_available_port(host: str, start_port: int, max_attempts: int = 10) -> int:
    """
    Find an available port.
    """
    for i in range(max_attempts):
        port = start_port + i
        if check_port(host, port):
            return port
    return None

if __name__ == "__main__":
    host = "0.0.0.0"
    port = 8000
    
    # Check port availability
    if not check_port(host, port):
        print(f"Warning: Port {port} is occupied, trying other ports...")
        available_port = find_available_port(host, port)
        
        if available_port is None:
            print(f"Error: Could not find an available port (range: {port}-{port + 9})")
            sys.exit(1)
        else:
            print(f"Starting service on port {available_port}")
            port = available_port
    
    # Start FastAPI application
    try:
        uvicorn.run(
            "app.main:app",
            host=host,
            port=port,
            reload=(settings.ENV == "development"),
            log_level="info"
        )
    except Exception as e:
        print(f"Startup failed: {e}")
        sys.exit(1)
